<?php
namespace app\api\middleware;
use app\api\model\SignInLog;
use app\api\model\Users;
use think\Request;

class Index
{
    public function handle(Request $request,\Closure $next){
        $url = trim($request->url(),'/');
        $url = trim(str_replace('api','',$url),'/');
        $url_array = explode('/',$url);
        $class = config('api.not_validate_user.class');
        $class_func = config('api.not_validate_user.class_func');
        if(!env('APP_DEBUG')){
            $auth_class = config('api.not_auth.class');
            $auth_class_func = config('api.not_auth.class_func');
            if(!in_array(strtolower($url),$auth_class_func)&&!in_array(strtolower($url_array[0]),$auth_class)){
                list($bool,$error) = AuthMiddleware::rend();
                if(!$bool){
                    return api_fail($error);
                }
            }
        }
        if(!in_array(strtolower($url),$class_func)&&!in_array(strtolower($url_array[0]),$class)){
            $token = $request->param('token','');
            if(empty($token)){
                return api_fail('请先登录',999);
            }
            $user = Users::where('token',$token)
                ->withoutField('delete_time')
                ->findOrEmpty()->toArray();
            if(empty($user)){
                return api_fail('请先登录',999);
            }
            $request->user = $user;
            SignInLog::add($user['id']);
        }else{
            $token = $request->param('token','');
            $user = Users::where('token',$token)
                ->withoutField('delete_time')
                ->findOrEmpty()->toArray();
            if(!empty($user)){
                $request->user = $user;
                SignInLog::add($user['id']);
            }
        }
        return  $next($request);
    }
}